
var data_name;
// Request Main Functions
request = {
    init: function() {
        this.create_request(".create_request");
        this.request_form_select(".request_form_select");
        this.submitRequest();
        //disable all fields
        this.disableAllFields();
        this.getRequestDetails();
        this.generateImportDialog();
        this.addViewer();
        this.getUserViewer();
        //for updating the fields by workflow stage

    },
    create_request: function(elements) {
        $("body").on("click", elements, function() {
            // Get Created form from the database
            $.ajax({
                url: "/ajax/formbuilder",
                type: "POST",
                data: {
                    action: "getForm"
                },
                dataType: 'json',
                success: function(result) {

                    var ret = "";
                    ret += '<h3>';
                    ret += '<i class="icon-reorder"></i> Forms.';
                    ret += '</h3>';
                    ret += '<div class="hr"></div>';
                    ret += '<div class="fields">';
                    ret += '<div class="label_basic"> Choose a form: </div>';
                    ret += '<div class="input_position">';
                    ret += '<select class="form-text choose_form" name="choose_form" id="choose_form" style="margin-top:5px;">';
                    ret += '<option value="0">----------------------------Select----------------------------</option>';
                    $.each(result, function(id, val) {
                        var form_name = result[id].form_name;
                        var form_id = result[id].form_id;
                        ret += '<option value="' + form_id + '">' + form_name + '</option>';
                    });
                    ret += '</select>';
                    ret += '</div>';
                    ret += '</div>';
                    ret += '<div class="fields">';
                    ret += '<div class="label_basic"></div>';
                    ret += '<div class="input_position" style="margin-top:5px;text-align:right;">';
                    ret += '<input type="button" class="btn-blueBtn request_form_select"  value="Ok">     ';
                    ret += '<input type="button" class="btn-basicBtn" id="popup_cancel" value="Cancel">';
                    ret += '</div>';
                    ret += '</div>';
                    jDialog(ret, '', '', '', '', function() {

                    });
                }
            });
        });
    },
    request_form_select: function(elements) {
        $("body").on("click", elements, function() {
            var choosen_form_id = $(".choose_form").val();
            if (choosen_form_id == "0") {
                showNotification({
                    message: "Please select a form to proceed.",
                    type: "error",
                    autoClose: true,
                    duration: 3
                });
            } else {
                window.location.replace("/workspace?view_type=request&formID=" + choosen_form_id);
            }
        });
    },
    submitRequest: function() {
        var self = this;
        $('body').on('click', '#goButton', function() { // server_date
            var pathname = window.location;
            if (getParametersName("view_type", pathname) == "preview") {
                return false;
            }

            ui.block()
            self.getKeywordFields();

            var req_ajax_data = $.ajax({
                url: "/ajax/getDateToday",
                type: "POST",
                data: {
                    "access": "get_date"
                },
                cache: false,
                dataType: "html",
                async: false,
                success: function(date) {
                    ui.unblock();
                    var server_date = date;
                    var invalid_datas = 0;
                    //set data validation
                    $(".setOBJ").each(function() {
                        // console.loaderg("TESTING ATTR SELECTOR JQUERY");
                        var data_obj_id = $(this).attr("data-object-id");
                        var the_field = $(this).find(".getFields_" + data_obj_id);
                        if (
                                typeof the_field.attr("required") != "undefined" ||
                                (typeof the_field.attr("required") == "undefined" && the_field.val() != "")
                                ) {
                            var invalid_field_data = 0;
                            if (the_field.attr("field-formula-validation")) {
                                if (the_field.attr("field-formula-validation") != null || the_field.attr("field-formula-validation") != '') {
                                    var field_data_validation_message = "Invalid value";
                                    if (typeof the_field.attr("field-formula-validation-message") != "undefined") {
                                        field_data_validation_message = "" + the_field.attr("field-formula-validation-message");
                                    }

                                    var field_data_validation_formula = the_field.attr("field-formula-validation");
                                    if (field_data_validation_formula.indexOf("@Date_Only(") >= 0) {
                                        field_data_validation_formula = field_data_validation_formula.replace(/@Date_Only\(/g, "Date_Only(");
                                    }
                                    var FDVF_splitted;
                                    try {
                                        FDVF_splitted = field_data_validation_formula.split(/<=|>=|==|!=|<|>|Date_Only\(|\(|\)|!/g);
                                        if (FDVF_splitted.length >= 1) {
                                            for (var u_i = 0; u_i < FDVF_splitted.length; u_i++) {
                                                FDVF_splitted[u_i] = $.trim(FDVF_splitted[u_i]);
                                            }
                                        }
                                    } catch (error) {
                                        //
                                    }
                                    console.log("OHH NOOOO!!")
                                    console.log(FDVF_splitted)
                                    //check if date or number or other
                                    try {
                                        var numeric_data_type = 0;
                                        var date_data_type = 0;
                                        var other_data_type = 0;
                                        var data_type_status = "";
                                        for (var ctr = 0; ctr < FDVF_splitted.length; ctr++) {
                                            if (typeof FDVF_splitted[ctr] == "undefined" || $.trim(FDVF_splitted[ctr]) == "") {
                                                continue;
                                            }
                                            string_field_name = $.trim(FDVF_splitted[ctr]).split("@").join("");
                                            field_affected_on_formula = $('[name="' + string_field_name + '"]');
                                            if (field_affected_on_formula.length >= 1) {
                                                var FAOF_val = field_affected_on_formula.val();
                                                if (typeof field_affected_on_formula.attr("data-input-type") != "undefined") {
                                                    if (field_affected_on_formula.attr("data-input-type") == "Currency") {
                                                        FAOF_val = FAOF_val.replace(/,/g, "");
                                                    }
                                                }
                                                if ($.isNumeric(FAOF_val)) {
                                                    numeric_data_type++;
                                                } else if (!isNaN(Date.parse(FAOF_val))) {
                                                    date_data_type++;
                                                } else if (FAOF_val == "") {
                                                    return true; // I return so that the required field validation of jewel will not be affected
                                                } else {
                                                    // alert("NAKO: "+string_field_name);
                                                    // alert(FAOF_val);
                                                    other_data_type++;
                                                }
                                            } else {
                                                // console.log("dito ung mga value na hindi fieldname")
                                                // console.log(string_field_name)
                                                if (("@" + string_field_name) == "@Now") {
                                                    date_data_type++;
                                                } else if (("@" + string_field_name) == "@Today") {
                                                    date_data_type++;
                                                } else {
                                                    if ($.isNumeric(string_field_name)) {
                                                        numeric_data_type++;
                                                    } else if (!isNaN(Date.parse(string_field_name))) {
                                                        date_data_type++;
                                                    } else {
                                                        // alert("eto:::"+string_field_name)
                                                        // alert("NAKO: "+string_field_name);
                                                        // alert($('[name="'+string_field_name+'"]').length);
                                                        other_data_type++;
                                                    }
                                                }
                                            }
                                        }
                                        var data_consitency_status = 0;
                                        if (numeric_data_type >= 1) {
                                            data_type_status = "numeric";
                                            data_consitency_status++;
                                        }
                                        if (date_data_type >= 1) {
                                            data_type_status = "date";
                                            data_consitency_status++;
                                        }
                                        if (other_data_type >= 1) {
                                            data_type_status = "unknown";
                                            data_consitency_status++;
                                            // console.log("ETOHAN unknown");
                                            // console.log(the_field)
                                            //requiredFields_v2(the_field);
                                            // alert(" value: "+the_field.val())
                                            //validationNotification(the_field, "Invalid value");
                                            //alert(44)
                                            //invalid_field_data++;
                                        }
                                        // console.log(
                                        //     "numeric:"+numeric_data_type+
                                        //     "\ndate:"+date_data_type+
                                        //     "\nother:"+other_data_type
                                        // )
                                    } catch (err) {

                                    }
                                    // alert("OK PA ETO TINGIN\n"+field_data_validation_formula)
                                    if (invalid_field_data >= 1) {
                                        //requiredFields_v2(the_field);
                                        // console.log("invalid field data other");
                                        // console.log(the_field)

                                        // alert("invalid field data")
                                        // alert(field_data_validation_formula)

                                        validationNotification(the_field, "Invalid value");
                                        //alert(33)
                                        invalid_datas++;
                                        return true;
                                    } else if (data_consitency_status != 1) {
                                        //requiredFields_v2(the_field);
                                        // console.log("data consistent");
                                        // console.log(the_field)
                                        validationNotification(the_field, "Invalid value");
                                        invalid_datas++;
                                        return true;
                                    } else {
                                        try {
                                            console.log("field_data_validation_formula")
                                            console.log(FDVF_splitted)
                                            // alert("OK")

                                            for (var ctr = 0; ctr < FDVF_splitted.length; ctr++) {
                                                console.log("validation", FDVF_splitted[ctr])
                                                if (typeof FDVF_splitted[ctr] == "undefined" || $.trim(FDVF_splitted[ctr]) == "") {
                                                    continue;
                                                }
                                                string_field_name = $.trim(FDVF_splitted[ctr]).split("@").join("");
                                                field_affected_on_formula = $('[name="' + string_field_name + '"]');
                                                console.log("ituu")
                                                console.log(field_affected_on_formula)
                                                if (field_affected_on_formula.length >= 1) {
                                                    var FAOF_val = field_affected_on_formula.val();
                                                    if (typeof field_affected_on_formula.attr("data-input-type") != "undefined") {
                                                        if (field_affected_on_formula.attr("data-input-type") == "Currency") {
                                                            FAOF_val = FAOF_val.replace(/,/g, "");
                                                        }
                                                    }
                                                    if (data_type_status == "numeric") {
                                                        field_data_validation_formula = field_data_validation_formula.replace("@" + string_field_name, FAOF_val);
                                                    } else if (data_type_status == "date") {
                                                        // console.log("@fieldName "+string_field_name+":"+FAOF_val); //DITO NA AKO
                                                        field_data_validation_formula = field_data_validation_formula.replace("@" + string_field_name, Date.parse(FAOF_val));
                                                    } else if ($.isNumeric(FAOF_val)) {
                                                        field_data_validation_formula = field_data_validation_formula.replace("@" + string_field_name, FAOF_val);
                                                    } else {
                                                        field_data_validation_formula = field_data_validation_formula.replace("@" + string_field_name, "\"" + FAOF_val + "\"");
                                                    }
                                                } else {
                                                    if (data_type_status == "numeric") {

                                                    } else if (data_type_status == "date") {
                                                        if (("@" + string_field_name) == "@Now") {
                                                            // console.log("@Now server_date: "+server_date);
                                                            field_data_validation_formula = field_data_validation_formula.replace("@" + string_field_name, Date.parse(server_date));
                                                        } else if (("@" + string_field_name) == "@Today") {
                                                            //alert(server_date);
                                                            // console.log("server_date: "+server_date)
                                                            var date_from_server = new Date(server_date);
                                                            var today_formatted_from_server = date_from_server.getFullYear() + "-" + (date_from_server.getMonth() + 1) + "-" + date_from_server.getDate();
                                                            // console.log("@Today today_formatted_from_server: "+today_formatted_from_server);
                                                            field_data_validation_formula = field_data_validation_formula.replace("@" + string_field_name, Date.parse(today_formatted_from_server));
                                                        } else {
                                                            // console.log("'yy-mm-dd' string_date: "+string_field_name);
                                                            field_data_validation_formula = field_data_validation_formula.replace(string_field_name, Date.parse(string_field_name));
                                                        }
                                                    }
                                                }
                                                // alert("11 "+FDVF_splitted[ctr])
                                                // alert("ETO TINGIN\n"+field_data_validation_formula+" "+ctr)
                                                // console.log(field_affected_on_formula)
                                                // console.log(field_data_validation_formula)
                                            }

                                            // alert(field_data_validation_formula)
                                            console.log("TESTING STRINGS");

                                            //console.log(field_data_validation_formula)
                                            // console.log(eval(field_data_validation_formula))
                                            // console.log(typeof eval(field_data_validation_formula))
                                            //$(".getFname").html(field_data_validation_formula)
                                            if (typeof eval(field_data_validation_formula) == "boolean") {
                                                console.log("pasok", field_data_validation_formula)
                                                console.log(eval(field_data_validation_formula))
                                                if (eval(field_data_validation_formula) == true) {
                                                    //ok
                                                    // alert(field_data_validation_formula)
                                                } else if (eval(field_data_validation_formula) == false) {
                                                    // alert(field_data_validation_formula + "ETO?")
                                                    // console.log("nag false");
                                                    // console.log(field_data_validation_formula);
                                                    //hindi ok
                                                    //the_field.attr("data-original-title","Invalid value");
                                                    //requiredFields_v2(the_field);
                                                    // console.log("LAST");
                                                    // console.log(the_field);
                                                    validationNotification(the_field, field_data_validation_message);
                                                    //alert(55);
                                                    invalid_datas++;
                                                }
                                            } else {
                                                //console.log("pasok32")
                                                validationNotification(the_field, "Invalid result on formula");
                                                invalid_datas++;
                                            }
                                        } catch (err) {
                                            console.log("error validation custom", field_data_validation_formula);
                                            validationNotification(the_field, "Invalid validation!!");
                                            invalid_datas++;
                                            //invalid_datas
                                        }
                                    }
                                }
                            }
                            if (the_field.attr("data-type")) {

                                if (the_field.attr("data-type") == "longtext") {

                                } else if (the_field.attr("data-type") == "float") {

                                    var field_Value = the_field.val();
                                    var fieldDataType = the_field.attr('data-input-type');

                                    if (fieldDataType == 'Currency') {
                                        field_Value = Number(field_Value.replace(/[^0-9\.]+/g, ""));
                                    }

                                    if (!$.isNumeric(field_Value)) {
                                        //requiredFields_v2(the_field);
                                        validationNotification(the_field, "Numbers only");
                                        invalid_datas++;
                                    }
                                }
                            }
                        }
                    });
                    if (invalid_datas >= 1) {
                        showNotification({
                            message: "Please correct the field values",
                            type: "error",
                            autoClose: true,
                            duration: 3
                        });
                    } else {
                        var selectedAction = $('#actionRequestButton option:selected').val();
                        var selectedNode = $('#actionRequestButton option:selected').attr('action');
                        var selectedWorkflowID = $('#actionRequestButton option:selected').attr('data-workflow-id');
                        var message = $('#actionRequestButton option:selected').attr('message');

                        if (!message || message == '') {
                            message = "Are you sure you want to proceed?";
                        }
                        $('#Node_ID').val(selectedNode);
                        $('#Workflow_ID').val(selectedWorkflowID);
                        if (selectedAction == '0') {
                            showNotification({
                                message: "Please select action",
                                type: "error",
                                autoClose: true,
                                duration: 3
                            });
                            return;
                        }
                        var hasRequiredError = 0;
                        $(".setOBJ .getFields").each(function() {
                            if ($(this).attr("required")) {
                                //design for required field here
                                if ($(this).attr("type") == "checkbox") {

                                } else {
                                    if ($(this).val() == "") {
                                        hasRequiredError++;
                                    }
                                }

                            }
                        })
                        if (hasRequiredError > 0) {
                            showNotification({
                                message: "Fill out all required fields",
                                type: "error",
                                autoClose: true,
                                duration: 3
                            });
                            return;
                        }
                        ;

                        repeater.getData();
                        jConfirm(message, '', '', '', '', function(r) {
                            if (r) {
                                self.formatCurrency();


                                //$('#frmrequest').submit();
                                // return;
                                $('#frmrequest').ajaxSubmit({
                                    success: function(data) {

                                        //  Get only the json data
                                        data = data.substring(data.indexOf('{'), data.length);
                                        console.log(data);

                                        var parsedData = JSON.parse(data);

                                        //console.log(parsedData);

                                        $.event.trigger({
                                            type: 'documentCreated',
                                            formId: parsedData
                                        });

                                        $.event.trigger({
                                            type: 'sendNotification',
                                            sendTo: [parsedData.Processor],
                                            notificationData: {
                                                notificationType: 'REQUEST_ACTION',
                                                requestData: parsedData
                                            }
                                        });
                                        //  redirect to home
                                        window.location = parsedData.headerLocation;

                                    }
                                });

                                ui.block();
                            }
                        });
                    }
                }
            });
        });
    },
    formatCurrency: function() {
        $('[data-input-type="Currency"]').each(function() {
            var currency = $(this).val();
            var newValue = Number(currency.replace(/[^0-9\.]+/g, ""));
            $(this).val(newValue);
        });
    },
    getRequestDetails: function() {

        var formId = $('#FormID').val();
        var self = this;
        var requestId = $("#ID").val();
        var currentUser = $("#CurrentUser").val();
        var tmpFieldEnabled = $("#fieldEnabled").val();
        //var tmpFieldHidden = $("#ID").val();
        //var tmpFieldRequired = $("#ID").val();
        var location = window.location.pathname;
        if (requestId != '0' && requestId != '') {
            if (location == '/workspace') {
                if ($('body').children(".submit-overlay").length == 0) {
                    var submit_overlay = $('<div class="submit-overlay" style="background:url(/images/loader/loader.gif);z-index:1002;background-repeat:no-repeat;background-attachment:fixed;background-color:rgba(200,200,200,0.5);background-position:center;position:fixed;width:100%;height:100%;text-align:center;vertical-align:middle;">Loading...</div>');
                    $('body').prepend(submit_overlay);
                }
            }
            var pathname = window.location;
            if (getParametersName("view_type", pathname) == "update") {
                var loc = "/ajax/printdetails";
            } else {
                var loc = "/ajax/requestdetails";
            }


            $.ajax({
                type: 'POST',
                url: loc,
                data: {
                    FormID: formId,
                    RequestID: requestId
                },
                success: function(result) {
                    //console.log(result)
                    // var resultJson = JSON.parse(result);
                    var resultJson = result;
                    for (var index in resultJson) {
                        for (var key in resultJson[index]) {
                            if ($('[name="' + key + '[]"]').attr("type") == "checkbox") {
                                $('[name="' + key + '[]"]').each(function() {
                                    if (resultJson[index][key]) {
                                        var checkbox_value = resultJson[index][key].split(",");
                                        var checkbox_value_new = resultJson[index][key].split("|^|");

                                        if (checkbox_value.indexOf($(this).val()) >= 0 || checkbox_value_new.indexOf($(this).val()) >= 0) {
                                            $(this).attr("checked", "checked")
                                        }
                                    }
                                });
                            } else if ($('[name="' + key + '"]').attr("type") == "radio") {
                                // $('[name="' + key +'"]').each(function(){
                                // });
                                $('[name="' + key + '"][value="' + resultJson[index][key] + '"]').prop("checked", true);
                            } else {
                                if (key == "fieldEnabled" || key == "fieldRequired" || key == "fieldHiddenValues") {
                                    $("." + key).text(resultJson[index][key]);
                                    if ($('[name="' + key + '"]').prop("tagName") == "TEXTAREA") {
                                        $('[name="' + key + '"]').text(resultJson[index][key]);
                                        $('[name="' + key + '"]').val(resultJson[index][key]);
                                    } else {
                                        $('[name="' + key + '"]').attr("value", resultJson[index][key]);
                                        $('[name="' + key + '"]').val(resultJson[index][key]);
                                    }
                                } else if (key == 'TrackNo') {
                                    $('[name="' + key + '"]').val(resultJson[index][key]);
                                    $('#trackno_display').text($('#TrackNo').val());
                                } else if (key == 'Requestor_Name') {
                                    $('[name="' + key + '"]').attr("value", resultJson[index][key]);
                                    $('#requestor_display').text(resultJson[index][key]);
                                } else if (key == 'Processor_Name') {
                                    $('[name="' + key + '"]').attr("value", resultJson[index][key]);
                                    $('#processor_display').text(resultJson[index][key]);
                                } else if (key == 'Status') {
                                    $('[name="' + key + '"]').val(resultJson[index][key]);
                                    $('#status_display').text($('#Status').val());
                                } else {
                                    if ($('[name="' + key + '"]').prop("tagName") == "TEXTAREA") {
                                        $('[name="' + key + '"]').text(resultJson[index][key]);
                                    } else if ($('[name="' + key + '"]').prop("tagName") == "SELECT") {
                                        $('[name="' + key + '"] option[value="' + resultJson[index][key] + '"]').attr("selected", "selected")
                                    } else {
                                        $('[name="' + key + '"]').attr("value", resultJson[index][key]);
                                        $('[name="' + key + '"]').val(resultJson[index][key]);
                                        //var photos = $('[name="' + key + '"]').parent().next().children().attr("src");

                                        //for submt request with photos
                                        var status = $("#status_display").html();
                                        if (currentUser != resultJson[index][key] && status.indexOf('Updated') >= 0) {
                                            $('[name="' + key + '"]').parent().parent().parent().parent().attr("data-type", "imageOnly");
                                        } else {
                                            $('[name="' + key + '"]').parent().parent().parent().parent().attr("data-type", "");
                                        }


                                        if (resultJson[index][key] != null) {
                                            $(".uploader2").hide();
                                            //$('[name="' + key + '"]').parent().parent().parent().parent().attr("data-type", "");
                                            $('[name="' + key + '"]').parent().find('img').attr("src", resultJson[index][key]);
                                        }
                                        if (resultJson[index][key] == "") {
                                            $('[name="' + key + '"]').parent().find('img').attr("src", "/images/avatar/large.png");
                                            //$('[name="' + key + '"]').parent().parent().parent().parent().parent().attr("data-type", "");
                                        }
                                        console.log("KEY:" + (key) + "  VALUE:" + (resultJson[index][key]));
                                    }
                                }

                            }
                        }
                    }

                    var imported = $("#imported").val();
                    if (imported == "1") {
                        $("[name='fieldEnabled']").val(tmpFieldEnabled);
                        $(".fieldEnabled").html(tmpFieldEnabled);
                        $("#imported").val('');
                    } else {
                        self.getButtons();
                    }
                    if ($('#LastAction').val() == 'null' || $('#LastAction').val() == null || $('#LastAction').val() == '') {
                        $('#lblprocessor_display').hide();
                        $('#processor_display').hide();
                    }

                    if ($(".submit-overlay").length >= 1) {
                        $(".submit-overlay").fadeOut(function() {
                            $(this).remove();
                        });
                    }
                    self.fieldEnabled();
                    self.fieldRequired();
                    self.fieldHiddenValues();
                    embeded_view.init();

                },
                dataType: "json",
                async: false
            });

            // $.post(
            //         '/ajax/requestdetails',
            //         {
            //             FormID: formId,
            //             RequestID: requestId
            //         },
            // function(result) {
            //     var resultJson = JSON.parse(result);
            //     for (var index in resultJson) {
            //         for (var key in resultJson[index]) {
            //             if ($('[name="' + key + '[]"]').attr("type") == "checkbox") {
            //                 $('[name="' + key + '[]"]').each(function() {
            //                     if (resultJson[index][key]) {
            //                         var checkbox_value = resultJson[index][key].split(",");
            //                         if (checkbox_value.indexOf($(this).val()) >= 0) {
            //                             $(this).attr("checked", "checked")
            //                         }
            //                     }
            //                 });
            //             } else if ($('[name="' + key + '"]').attr("type") == "radio") {
            //                 // $('[name="' + key +'"]').each(function(){
            //                 // });
            //                 $('[name="' + key + '"][value="' + resultJson[index][key] + '"]').prop("checked", true);
            //             } else {
            //                 if (key == "fieldEnabled" || key == "fieldRequired" || key == "fieldHiddenValues") {
            //                     $("." + key).text(resultJson[index][key]);
            //                     if ($('[name="' + key + '"]').prop("tagName") == "TEXTAREA") {
            //                         $('[name="' + key + '"]').text(resultJson[index][key]);
            //                     } else {
            //                         $('[name="' + key + '"]').attr("value", resultJson[index][key]);
            //                     }
            //                 } else if (key == 'TrackNo') {
            //                     $('[name="' + key + '"]').val(resultJson[index][key]);
            //                     $('#trackno_display').text($('#TrackNo').val());
            //                 } else if (key == 'Requestor_Name') {
            //                     $('[name="' + key + '"]').attr("value", resultJson[index][key]);
            //                     $('#requestor_display').text(resultJson[index][key]);
            //                 } else if (key == 'Processor_Name') {
            //                     $('[name="' + key + '"]').attr("value", resultJson[index][key]);
            //                     $('#processor_display').text(resultJson[index][key]);
            //                 } else if (key == 'Status') {
            //                     $('[name="' + key + '"]').val(resultJson[index][key]);
            //                     $('#status_display').text($('#Status').val());
            //                 } else {
            //                     if ($('[name="' + key + '"]').prop("tagName") == "TEXTAREA") {
            //                         $('[name="' + key + '"]').text(resultJson[index][key]);
            //                     } else {
            //                         $('[name="' + key + '"]').attr("value", resultJson[index][key]);
            //                     }
            //                 }

            //             }
            //         }
            //     }

            //     var imported = $("#imported").val();
            //     if (imported == "1") {
            //         $("[name='fieldEnabled']").val(tmpFieldEnabled);
            //         $(".fieldEnabled").html(tmpFieldEnabled);
            //         $("#imported").val('');
            //     } else {
            //         self.getButtons();
            //     }
            //     if ($('#LastAction').val() == 'null' || $('#LastAction').val() == null || $('#LastAction').val() == '') {
            //         $('#lblprocessor_display').hide();
            //         $('#processor_display').hide();
            //     }

            //     if ($(".submit-overlay").length >= 1) {
            //         $(".submit-overlay").fadeOut(function() {
            //             $(this).remove();
            //         });
            //     }
            //     self.fieldEnabled();
            //     self.fieldRequired();
            //     self.fieldHiddenValues();
            //     embeded_view.init();

            // });
        } else {
            self.fieldEnabled();
            self.fieldRequired();
            self.fieldHiddenValues();
            computed.init();
            // $(".viewer_action").append('<button class="btn-basicBtn padding_5 cursor tip addViewer" data-original-title="Add Viewer"><i class="icon-user"></i></button>')
            // $(".tip").tooltip();
            //   self.getButtons();
        }


    },
    getButtons: function() {
        var buttons = ($('#LastAction').val() === undefined || $('#LastAction').val() === '') ? "" : JSON.parse($('#LastAction').val());
        var workflowId = $('#WorkflowId').val();
        var currentUser = $("#CurrentUser").val();
        var processor = $("#Processor").val();
        var requestId = $("#ID").val();
        var requestor_id = $("#Requestor").val();
        $('#actionRequestButton').html('<option value="0">-------------Select Button-------------</option>');
        if (!processor) {
            return;
        }
        processor = processor.split(",");
        if (processor.indexOf(currentUser) >= 0) {
            for (var index in buttons) {
                $('#actionRequestButton').append('<option value="' + buttons[index].button_name + '" data-workflow-id="' + workflowId + '" action="' + buttons[index].child_id + '" message = "' + buttons[index].message + '">' + buttons[index].button_name + '</option>');
            }

            if (requestId != '0' && buttons != null) {
                $('#actionRequestButton').append('<option value="Save" data-workflow-id="Save" action="Save">Save</option>');
                $(".tip").tooltip();
            }
        }

        var editors = String($("#Editor").val()).split(',');

        if (editors.indexOf(currentUser) >= 0) {
            if (requestId != '0' && buttons != null) {
                //$('#actionRequestButton').append('<option value="Save" data-workflow-id="Save" action="Save">Save</option>');
                $('#actionRequestButton').append('<option value="Save" data-workflow-id="Save" action="Save">Save</option>');
                $(".tip").tooltip();
            }
        }
        if (requestId != '0' && buttons != null) {
            if (requestor_id == currentUser) {
                $('#actionRequestButton').append('<option value="Cancel" data-workflow-id="Cancel" action="Cancel">Cancel</option>');
            }
        }
        if (processor.indexOf(currentUser) >= 0 || requestor_id == currentUser) {
            $(".viewer_action").append('<div class=" fl-createViewreq fl-buttonEffect btn-basicBtn padding_5 cursor tip addViewer" data-original-title="Add Viewer"><i class="icon-user fa fa-user"></i></div>')
            $.post("/ajax/request_viewer", {action: "getUsers"}, function(data) {
                data_name = JSON.parse(data);
            })
            // $(".viewer_action").html('<button class="btn-basicBtn padding_5 cursor tip form-readers" data-original-title="Viewers"><i class="icon-book"></i></button>');
        }

    },
    addCommentRequest: function() {
        $("body").on("click", "#reply", function(e) {
            var fID = $(this).attr("data-f-id");
            replyComment(this, fID);
        });
    },
    disableAllFields: function() {
        $(".setOBJ .getFields").attr("disabled", "disabled");

        //hide picklist if enabled
        $(".pickListButton").hide();
    },
    fieldEnabled: function() {
        var fields = ""
        var requestId = $("#ID").val();
        var requestor_id = $("#Requestor").val();
        var currentUser = $("#CurrentUser").val();
        if (requestor_id == currentUser || requestId == 0) {
            fields = $(".fieldEnabled_default").text();
        } else {
            fields = $(".fieldEnabled").text();
        }
        fields = (fields == "null" ? "" : fields);
        if (fields) {
            fields = JSON.parse(fields);
            $.each(fields, function(key, value) {
                if ($('[name="' + value + '[]"]').attr("type") == "checkbox") {
                    $('[name="' + value + '[]"]').attr("disabled", false);
                } else {
                    //show picklist if enabled
                    $('[name="' + value + '"]').closest(".setOBJ").find(".pickListButton").show();
                    $('[name="' + value + '"]').attr("disabled", false);
                }
            })
        }
    },
    fieldRequired: function() {
        var fields = ""
        var requestId = $("#ID").val();
        var requestor_id = $("#Requestor").val();
        var currentUser = $("#CurrentUser").val();
        if (requestor_id == currentUser || requestId == 0) {
            fields = $(".fieldRequired_default").text()

        } else {
            fields = $(".fieldRequired").text()
        }
        fields = (fields == "null" ? "" : fields);
        if (fields) {
            fields = JSON.parse(fields);
            $.each(fields, function(key, value) {
                $('[name="' + value + '"]').attr("required", "required");
            })
        }
    },
    fieldHiddenValues: function() {
        var fields = ""
        var requestId = $("#ID").val();
        var requestor_id = $("#Requestor").val();
        var currentUser = $("#CurrentUser").val();
        if (requestor_id == currentUser || requestId == 0) {
            fields = $(".fieldHiddenValues_default").text()

        } else {
            fields = $(".fieldHiddenValues").text()
        }
        fields = (fields == "null" ? "" : fields);
        if (fields) {
            fields = JSON.parse(fields);
            $.each(fields, function(key, value) {
                if ($('[name="' + value + '[]"]').attr("type") == "checkbox") {
                    $('[name="' + value + '[]"]').closest(".setOBJ").addClass("display2");
                } else {
                    $('[name="' + value + '"]').closest(".setOBJ").addClass("display2");
                }
            })
        }
    },
    getKeywordFields: function() {
        var keywordFields = [];
        $('.pickListButton').each(function() {
            var inputField = $(this).attr('return-field');
            var inputFieldName = $('#' + inputField).attr('name');
            var inputCode = $('#' + inputField).attr('code');
            keywordFields.push({
                Field: inputFieldName,
                Code: inputCode
            });
        });
        console.log(keywordFields);
        $('#KeywordsField').val(JSON.stringify(keywordFields));
    },
    setRepeaterContent: function() {
        var content = JSON.parse($('#Repeater_Data').val());

        console.log(content);
        return;
        for (var index = 0; index <= rowCount - 1; index++) {
            var fieldName = content[index].FieldName;
            var fieldContainer = $('[name="' + fieldName + '"]').closest('.input_position_below');

            var containerPanel = $(fieldContainer).closest('.setOBJ');
            var buttonContainer = $(containerPanel).closest('tr');

            $(buttonContainer).find('.rep-add-spec-row').each(function() {
                if (index != 0) {
                    $(this).click();
                }
            });
        }

        $('[repeater-table="true"]').find('tr').each(function(row) {
            $(this).find('.getFields ').each(function(column) {
                var value = JSON.parse(content[column].Values);

                switch ($(this).attr('type')) {
                    case "checkbox":
                        if ($(this).val() === value[row]) {
                            $(this).prop('checked', true);
                        } else {
                            $(this).prop('checked', false);
                        }
                        break;
                    case "radio":
                        break;
                    default :
                        break;
                }

                //$(this).val(value[row]);
            });
        });
    },
    getRepeaterContent: function() {
        var repeaters = [];
        $('[repeater-table="true"]').each(function() {
            $(this).find('tr:first').each(function() {
                $(this).find('.getFields').each(function() {
                    var thisName = $(this).attr('name');
                    var data = [];
                    var fields = [];

                    $('[rep-original-name="' + thisName + '"], [name="' + thisName + '"]').each(function() {
                        var fieldType = $(this).attr('type');
                        var copyName = $(this).attr('name');
                        if (fields.indexOf(copyName) === -1) {
                            switch (fieldType) {
                                case "checkbox":
                                    var addedValue = [];
                                    $('[name="' + copyName + '"]').each(function() {
                                        if ($(this).prop('checked')) {
                                            addedValue.push($(this).val());
                                        }
                                    });
                                    break;
                                case "radio":
                                    var addedValue = [];
                                    $('[name="' + copyName + '"]').each(function() {
                                        if ($(this).prop('checked')) {
                                            addedValue.push($(this).val());
                                        }
                                    });
                                    break;
                                default :
                                    var addedValue = $(this).val();
                                    break;
                            }

                            var valueGenerated = JSON.stringify(addedValue);

                            fields.push(copyName);
                            data.push(valueGenerated);
                        }
                    });

                    repeaters.push({
                        FieldName: thisName,
                        Data: data
                    });
                });
            });
        });

        console.log(repeaters);
        $('#Repeater_Data').val(JSON.stringify(repeaters));
    },
    generateImportDialog: function() {
        //$('body').on('click', '[link-type="import"]', function() {
        //    var formId = $(this).attr('link-form-id');
        //    var ret = '<h3 class="fl-margin-bottom"><i class="icon-asterisk"></i> Request Import</h3>' + 
        //            '<form action ="/ajax/request_import" class="fl-importBtn" method="POST" enctype="multipart/form-data"> ' +
        //            '<div class="hr"></div>' +
        //            '<input class="display" type="text" name="FormID" value = "' + formId + '" />' +
        //            '<div class="fields"><div class="label_below2 fl-margin-bottom">Please select file: </div><div class="input_position">' +
        //            '<div id="uniform-fileInput" class="uploader label_below2">' +
        //            '<input type="file" data-action-id="3" value="upload" name="fileupload" id="uploadForm" size="24" style="opacity: 0;" class="import_request_file" />' +
        //            '<span id="uploadFilename_3" class="filename import_request_txt">No file selected</span>' +
        //            '<span class="action">Choose File</span>' +
        //            '</div>' +
        //            '</div></div>' +
        //            '<div class="fields"><div class="label_below2"></div><div class="input_position" style="color:#ff0000;font-style:italic;margin-top:5px;">Note: File should be in Comma Separated Value(CSV) file format </div></div>' +
        //            '<div class="fields"><div class="label_below2"></div><div class="input_position" style="margin-top:5px;"><input type="submit" class="btn-blueBtn fl-margin-right" value="Ok"> <input type="button" class="btn-basicBtn" id="popup_cancel" value="Cancel"></div></div>' +
        //            ' </form>';
        //    var newDialog = new jDialog(ret, '', '', '', '', function() {
        //
        //    });
        //    newDialog.themeDialog("modal2");
        //});
        $('body').on('click', '[link-type="import"]', function() {
            var formId = $(this).attr('link-form-id');
            var ret = '<h3 class="fl-margin-bottom"><i class="icon-asterisk"></i> Request Import</h3>' + 
                    '<form action ="/ajax/request_import" class="fl-importBtn importCSVForm" method="POST" enctype="multipart/form-data"> ' +
                    '<div class="hr"></div>' +
                    '<input class="display" type="text" name="FormID" value = "' + formId + '" />' +
                    '<div class="fields"><div class="label_below2 fl-margin-bottom">Please select file: </div><div class="input_position">' +
                    '<div id="uniform-fileInput" class="uploader label_below2">' +
                    '<input type="file" data-action-id="3" value="upload" name="fileupload" id="uploadForm" size="24" style="opacity: 0; width:100%;" class="import_request_file" />' +
                    '<span id="uploadFilename_3" class="filename import_request_txt">No file selected</span>' +
                    '<span class="action">Choose File</span>' +
                    '</div>' +
                    '</div></div>' +
                    '<div class="fields"><div class="label_below2"></div><div class="input_position" style="color:#ff0000;font-style:italic;margin-top:5px;">Note: File should be in Comma Separated Value(CSV) file format </div></div>' +
                    '<div class="fields"><div class="label_below2"></div><div class="input_position" style="margin-top:5px;"><input type="button" class="btn-blueBtn fl-margin-right importCSV" value="Ok"> <input type="button" class="btn-basicBtn" id="popup_cancel" value="Cancel"></div></div>' +
                    ' </form>';
            var newDialog = new jDialog(ret, '', '', '', '', function() {

            });
            newDialog.themeDialog("modal2");
        });


        $("body").on("click",".importCSV",function(){
            $(".importCSVForm").submit();
        })
    },
    // Print actual Form
    printForm: function() {
        var self = this;
        $("body").on("click", ".printForm", function() {
            $(".getFields").each(function() {
                if ($(this).attr("type") == "radio") {
                    if ($(this).is(":checked")) {
                        $(this).attr("checked", "checked");
                    }
                }
            })
            var pathname = window.location;
            if (getParametersName("view_type", pathname) == "preview") {
                self.print_content("", "");
            } else {
                var ret = '<h3 class="fl-margin-bottom"><i class="icon-print fa fa-print"></i> Print settings</h3>';
                ret += '<div class="hr"></div>';
                ret += '</div>';
                ret += '<div id="comment-container" style="position: relative; margin: 0px auto; padding: 0px; width: 100%; height: 100px;overflow: hidden;" class="ps-container">'
                ret += '<div class="content-dialog sub-container-comment requestComment" style="width: 95%;height: auto;">';
                ret += "<div style='font-weight: bold;margin-bottom: 10px;'>Choose data you want to include in your printing.</div>";
                ret += '<div style="margin-left:10px">';
                ret += "<label style=''><input type='checkbox' class='print-setting-inc css-checkbox' value='comment' id='print-setting-inc_comment'><label for='print-setting-inc_comment' class='css-label'></label> Comments</label><br /><br />";
                ret += "<label style=''><input type='checkbox' class='print-setting-inc css-checkbox' value='audit-log' id='print-setting-inc_audit-logs'><label for='print-setting-inc_audit-logs' class='css-label'></label> Audit Logs</label>";
                ret += '</div>';
                ret += '</div>';
                ret += '</div>';
                ret += '<div class="fields">';
                ret += '<div class="label_basic"></div>';
                ret += '<div class="input_position" style="margin-top:5px;text-align:right;">';
                ret += ' <input type="button" class="btn-blueBtn fl-margin-right" id="print-setup" value="Print">';
                ret += ' <input type="button" class="btn-basicBtn" id="popup_cancel" value="Close">';
                ret += '</div>';
                ret += '</div>';
                jDialog(ret, "", "", "200", "", function() {

                });
                $("#print-setup").click(function() {
                    var arrChecked = array_store(".print-setting-inc", "checkbox");
                    self.getLogs(function(logs) {
                        self.getComments(function(comments) {
                            if (arrChecked.indexOf("comment") == -1) {
                                comments = "";
                            }
                            if (arrChecked.indexOf("audit-log") == -1) {
                                logs = "";
                            }
                            self.print_content(logs, comments);
                        })
                    })
                })
            }

            // $(".getFields").each(function() {
            //     if ($(this).attr("type") == "radio") {
            //         if ($(this).is(":checked")) {
            //             $(this).attr("checked", "checked");
            //         }
            //     }
            // })
            // var pathname = window.location;
            // if (getParametersName("view_type", pathname) == "preview") {
            //     self.print_content("", "");
            // } else {
            //     self.getLogs(function(logs) {
            //         self.getComments(function(comments) {
            //             self.print_content(logs, comments);
            //         })
            //     })
            // }

        });
    },
    print_content: function(logs, comments) {
        var ret = ""
        var widthForm = $(".preview_content").width();
        var heightForm = $(".preview_content").parent().height();
        var formName = $(".getFname").html();
        ret += '<link rel="stylesheet" type="text/css" href="/css/style.css" />';
        ret += '<link rel="stylesheet" type="text/css" href="/css/font-awesome.css" />';
        ret += '<link rel="stylesheet" type="text/css" href="/css/reset.css" />';
        ret += '<link rel="stylesheet" href="/css/jquery-ui.css" />';
        ret += '<link rel="stylesheet" href="/js/functions/formbuilder.css" />';


        var mywindow = window.open('', formName, 'height=' + heightForm + ',width=' + widthForm);
        mywindow.document.write('<html><head><title>' + formName + '</title>');
        $("link, style").each(function() {
            $(mywindow.document.head).append($(this).clone())
        });



        mywindow.document.write('</head><body>');
        mywindow.document.write('<div id="previewToPrint" style="height:' + heightForm + '">');
        mywindow.document.write('</div>');
        // mywindow.document.write($(".preview_content").clone(true)[0].outerHTML);
        var htmlClone = $(".preview_content").clone(true);
        $(htmlClone).appendTo(mywindow.document.getElementById("previewToPrint"));
        var selectIds = "";
        var select = "";
        var val = "";
        console.log($(".preview_content").find("select .getFields").length)
        $(".preview_content").find("select").each(function() {
            if ($(this).hasClass("getFields")) {
                selectIds = this.id;
                val = $(this).val()
                select = $(this).clone(true).val(val);
                $(mywindow.document.getElementById(selectIds)).parent().html(select);
            }
        });


        if (logs != "") {
            mywindow.document.write("<div class='hr'></div>");
            mywindow.document.write(logs);
        }
        if (comments != "") {
            mywindow.document.write("<div class='hr'></div>");
            mywindow.document.write(comments);
        }

        mywindow.document.write('</body></html>');
        var tbWrapper = mywindow.document.getElementsByClassName("table-wrapper");
        var parentTbWrapper = "";
        for (var i in tbWrapper) {
            if (tbWrapper[i].style) {
                tbWrapper[i].style.display = "block";
            }
            parentTbWrapper = tbWrapper[i].parentNode;
            if (parentTbWrapper) {
                parentTbWrapper.style.overflow = "";
            }

        }
        var setObj = mywindow.document.getElementsByClassName("setOBJ");
        for (var i in setObj) {
            if (setObj[i].style) {
                if (setObj[i].style.display != "none") {
                    setObj[i].style.display = "block";
                }
            }

        }

        // var select = mywindow.document.getElementsByTagName("select");
        // var classN = "";
        // for(var i in select){
        //     if(select[i].className){
        //         classN = select[i].className.split(" ");
        //         if(classN.indexOf("getFields")!=-1){
        //             mywindow.document.name(select[i].name).setAttribute("selected","selected");
        //         }
        //     }
        // }
        mywindow.print();
        mywindow.close();
    },
    getLogs: function(callback) {
        var request_id = $('#ID').val();
        var form_id = $('#FormID').val();
        //view of logs



        $.post('/ajax/getRequestLogs', {
            formId: form_id,
            request_Id: request_id
        }, function(data) {
            var result = JSON.parse(data);
            var ret = '<div><h3 class="fl-margin-bottom"><i class="icon-book fa fa-book"></i> Audit Logs</h3>';
            ret += '<div class="hr"></div>';
            ret += '<div id="logs-container" style="position: relative; margin: 0px auto; padding: 0px; width: 100%; height: auto;" class="ps-container">'
            ret += '<div class="content-dialog sub-container-logs" style="width: 95%;">'
            for (var index in result) {
                ret += '<div class="reply" id="reply_80" style="width:95%">';
                ret += '<a class="message-img" href="#">' + result[index].created_by.image + '</a>';
                ret += '<div class="message-body">';
                ret += '<div class="text" id="postText_80"><p>' + result[index].details + '</p></div>';
                ret += '<p class="attribution">by <a href="#non">' + result[index].created_by.display_name + '</a> at <label class="timeago" title="' + result[index].date_created + '">' + result[index].date_created + '</label>';
                ret += '</p></div>';
                ret += '</div>';
            }
            ret += '</div>';
            ret += '</div>';
            ret += '</div>';
            callback(ret);
            //$("label.timeago").timeago();
        });
    },
    getComments: function(callback) {
        //view of comment
        $(".load-mr").show();
        var reqID = $("#ID").val();
        var formID = $("#FormID").val();
        $.ajax({
            type: "POST",
            url: "/ajax/post",
            dataType: "json",
            cache: false,
            data: "action=getComment" + "&postID=" + reqID + "&formID=" + formID,
            success: function(result) {
                var ret = '';
                if (result) {
                    ret = '<div><h3><i class="icon-comment"></i> Comments / Suggestion</h3>';
                    ret += '<div class="hr"></div>';
                    ret += '<div id="comment-container" style="position: relative; margin: 0px auto; padding: 0px; width: 100%; height: auto;" class="ps-container">'
                    ret += '<div class="content-dialog sub-container-comment requestComment" style="width: 95%;height: auto;">';
                    for (var a = 0; a < result.length; a++) {
                        var postDetails = "print";
                        var uploadedDetails = null;
                        var likeDetails = null;
                        var comments = result[a];
                        ret += replyPost(postDetails, uploadedDetails, likeDetails, comments);
                    }
                    ret += '</div>';
                    ret += '</div>';
                    ret += '</div>';
                }
                callback(ret)
            }
        });
    },
    /* Remove Files attached on the request
     ================================================== */
    removeFiles: function() {
        $("body").on("click", ".removeFiles", function() {
            var self = $(this);
            var filename = $(this).attr("data-file");
            var file_location = $(this).attr("data-location");
            con = "Are you sure do you want to delete this?";
          var newConfirm = new  jConfirm(con, 'Confirmation Dialog', '', '', '', function(r) {
                if (r == true) {
                    $.post("/ajax/files", {action: "deleteFiles", filename: filename, file_location: file_location}, function(e) {

                        if (e == "File was successfully deleted.") {
                            self.parent().parent().parent().remove();
                        }
                    });
                }
            });
            newConfirm.themeConfirm("confirm2", {'icon':'<i class="fa fa-exclamation-triangle fl-margin-right" style="color:#f00; font-size:15px;"></i>'});
        });
    },
    addViewer: function() {
        var requestId = $("#ID").val();
        var form_id = $('#FormID').val();
        var self = this;
        $("body").on("click", ".addViewer", function() {
            //add viwer
            var ret = '<h3 class="fl-margin-bottom"><i class="icon-book"></i>Add Viewer</h3>';
            ret += '<div class="hr"></div>';
            ret += '</div>';
            ret += '<div id="add-viewer-container" style="position: relative; margin: 0px auto; padding: 0px; width: 100%; height: 300px;overflow: hidden;" class="ps-container">'
            ret += '<div class="content-dialog sub-container-add-viewer" style="width: 95%;height: auto;">'
            ret += '<center><img src="/images/loader/loader.gif" class="load-mr" style="display: inline;margin-top:20%;"></center>'
            //ret += '<textarea class="mention display" id="mention-name" placeholder="" data-mentions-input="true" style="height: 42px;background-transparent"></textarea>';
            ret += '</div>'
            ret += '</div>'
            ret += '<div class="fields">';
            ret += '<div class="label_basic"></div>';
            ret += '<div class="input_position" style="margin-top:5px;text-align:right;">';
            ret += ' <input type="button" class="btn-basicBtn" id="popup_cancel" value="Close">';
            ret += ' <input type="button" class="btn-basicBtn saveViewer" value="Save">';
            ret += '</div>';
            ret += '</div>';
            jDialog(ret, "", "", "", "", function() {
            });
            // $(".sub-container-add-viewer").perfectScrollbar();

            //         $.post("/ajax/request_viewer",{action:"getUsers"},function(data){
            //             data = JSON.parse(data);
            // $(".sub-container-add-viewer").html('<textarea class="mention" id="mention-name" placeholder="" data-mentions-input="true" style="height: 42px;background-transparent"></textarea>')
            //             $("#mention-name").mention_only({
            //                 json : data

            //             });
            //         })
            if (requestId != 0) {
                var returnViewer = "";
                $.post("/ajax/request_viewer", {action: "getRequestViewer", request_id: requestId, form_id: form_id}, function(data) {
                    data = JSON.parse(data);
                    for (var i in data) {
                        returnViewer += "<div class='mentionSelected' data-id=" + data[i]['id'] + "><i class='removeTagg_i icon-remove-sign' style='margin-right: 5px;cursor: pointer;'></i>" + data[i]['name'] + "</div>";
                    }
                    $(".sub-container-add-viewer").html('<textarea class="mention" id="mention-name" placeholder="" data-mentions-input="true" style="height: 42px;background-transparent"></textarea>')
                    $("#mention-name").mention_only({
                        json: data_name

                    });
                    $(".mention").before(returnViewer);
                })
            }
            self.saveViewer();
        })
    },
    saveViewer: function() {
        var array_search = new Array();
        var requestId = $("#ID").val();
        var form_id = $('#FormID').val();
        $(".saveViewer").click(function() {
            if ($('body').children(".submit-overlay").length == 0) {
                var submit_overlay = $('<div class="submit-overlay" style="background:url(/images/loader/loader.gif);z-index: 100000;background-repeat:no-repeat;background-attachment:fixed;background-color:rgba(200,200,200,0.5);background-position:center;position:fixed;width:100%;height:100%;text-align:center;vertical-align:middle;">Loading...</div>');
                $('body').prepend(submit_overlay);
            }
            $(".mentionSelected").each(function() {
                array_search.push($(this).attr("data-id"));
            })
            if(array_search.length==0){
                showNotification({
                    message: "Please enter alteast 1 user",
                    type: "error",
                    autoClose: true,
                    duration: 3
                });
                if (submit_overlay.length >= 1) {
                    submit_overlay.fadeOut(function() {
                        $(this).remove();
                    });
                }
                return;
            }
            if (requestId != 0) {
                //save to database
                $.post("/ajax/request_viewer", {action: "saveViewer", array_search: array_search, requestId: requestId, form_id: form_id}, function(data) {
                    if (submit_overlay.length >= 1) {
                        submit_overlay.fadeOut(function() {
                            $(this).remove();
                        });
                    }
                    showNotification({
                        message: "Viewer Saved",
                        type: "success",
                        autoClose: true,
                        duration: 3
                    });
                    $("#popup_cancel").click();
                    array_search = [];
                })
            } else {

            }
        })
    },
    getUserViewer: function() {
        var requestId = $("#ID").val();
        var form_id = $('#FormID').val();
        var self = this;
        $.post("/ajax/request_viewer", {action: "getTaggedUsers", requestId: requestId, form_id: form_id}, function(data) {
            if (data == 1) {
                $(".viewer_action").append('<button class="btn-basicBtn padding_5 cursor tip removetagRequest" data-original-title="Remove Tag"><i class="icon-power-off"></i></button>')
                $(".tip").tooltip();
                self.removetagRequest();
            }
        })
    },
    removetagRequest: function() {
        var requestId = $("#ID").val();
        var form_id = $('#FormID').val();
        var self = this;
        $(".removetagRequest").click(function() {
            jConfirm('Are you sure you want to remove Tag?', '', '', '', '', function(r) {
                if (r) {
                    if ($('body').children(".submit-overlay").length == 0) {
                        var submit_overlay = $('<div class="submit-overlay" style="background:url(/images/loader/loader.gif);z-index: 100000;background-repeat:no-repeat;background-attachment:fixed;background-color:rgba(200,200,200,0.5);background-position:center;position:fixed;width:100%;height:100%;text-align:center;vertical-align:middle;">Loading...</div>');
                        $('body').prepend(submit_overlay);
                    }
                    $.post("/ajax/request_viewer", {action: "removetagRequest", requestId: requestId, form_id: form_id}, function(data) {
                        if (submit_overlay.length >= 1) {
                            submit_overlay.fadeOut(function() {
                                $(this).remove();
                            });
                        }
                        showNotification({
                            message: "Tagged Removed",
                            type: "success",
                            autoClose: true,
                            duration: 3
                        });
                        // $("#popup_cancel").click();
                        // $(".removetagRequest").remove();
                        // $(".tooltip").remove();
                        setTimeout(function() {
                            window.location = "/application?id=" + data;
                        }, 2000)
                    })
                }
            });
        })
    }
}

$(document).ready(function() {
    var dis_pathname = window.location.pathname;
    if (dis_pathname != "/user_view/workspace" && dis_pathname!="/user_view/formbuilder") {
        // Request Main Functions
        // create a request
        // request.create_request(".create_request");
        // request.request_form_select(".request_form_select");
        // request.submitRequest();

        request.addCommentRequest();
        request.printForm(); // Print Form
        request.removeFiles(); // download attachment
        request.init();
        $("body").on("change", ".import_request_file", function() {
            var fpath = $(this).val().replace(/\\/g, '/');
            var a = fpath.split("/");
            var aParameter = a.length;
            //var fnameLength = fname.length;
            $(".import_request_txt").text("Filename: " + a[aParameter - 1]);
        });
    }
})



function validationNotification(element_affected, message) {
    if (typeof message == "undefined") {
        //catch errr
        message = '';
    }
    var this_element = $(element_affected);
    var this_element_name = $(element_affected).attr("name");
    var element_container = this_element.parent();
    var element_ptop = this_element.parents(".setOBJ").eq(0).position().top;
    var element_pleft = this_element.parents(".setOBJ").eq(0).position().left;
    var element_pright = this_element.parents(".setOBJ").eq(0).position().left + this_element.parents(".setOBJ").eq(0).outerWidth();
    var element_pbottom = this_element.parents(".setOBJ").eq(0).position().top + this_element.parents(".setOBJ").eq(0).outerHeight();
    var noti_ele = $(
            '<div class="custom-notification" unique-attr="' + this_element_name + '" style="padding:5px;z-index:100;"><div class="arrow-left"></div>' + message + '</div>'
            )

    this_element.addClass("frequired-red");
    if (element_container.children(".custom-notification[unique-attr='" + this_element_name + "']").length == 0) {
        // element_container.append(noti_ele);
        element_affected.parents(".setOBJ").eq(0).after(noti_ele);
        $(noti_ele).css({
            "top": (element_ptop) + "px",
            "left": (element_pright + 5) + "px",
            "padding": "8px",
            "color": "#ffffff",
            "text-align": "center",
            "text-decoration": "none",
            "position": "absolute",
            "-webkit-border-radius": "4px",
            "-moz-border-radius": "4px",
            "border-radius": "4px",
            "background-color": "#000000"
        });
        $(noti_ele).children(".arrow-left").eq(0).css({
            "width": "0px",
            "height": "0px",
            "border-top": "10px solid transparent",
            "border-right": "10px solid #000000",
            "position": "absolute",
            "top": "5px",
            "left": "0px",
            "margin-left": "-5px"
        });
        var mouse_entered = "not yet";
        noti_ele.on({
            "mouseenter": function() {
                if (mouse_entered == "not yet") {
                    noti_ele.fadeOut(2500, function() {
                        $(this).remove();
                    });
                    mouse_entered = "yes";
                }
            }
        });
        this_element.on({
            "focusin": function() {
                $(this).removeClass("frequired-red");
                if (noti_ele.length >= 1) {
                    noti_ele.fadeOut(1000, function() {
                        $(this).remove();
                    });
                }
            }
        });
    }
}


var embeded_view = {
    init: function() {
        this.load();
    },
    load: function() {
        var self = this;
        $('.embed-view-container').each(function() {
            var formId = $(this).attr('embed-source-form-val-id');
            var fieldReference = $(this).attr('embed-result-field-val');
            var fieldValue = $('[name="' + fieldReference + '"]').val();
            var fieldFilter = $(this).attr('embed-source-lookup-active-field-val');
            var fieldReferenceType = $(this).attr('rfc-choice');

            if (fieldReferenceType == 'computed') {
                var thisFormula = $(this).attr('embed-computed-formula');
                var formulaDoc = new Formula(thisFormula);
                fieldValue = formulaDoc.getEvaluation();
            }

            var container = this;
            if (fieldValue !== '' && fieldValue !== null && fieldValue !== 'null') {
                var reference = {
                    FormID: formId,
                    FieldReference: fieldReference,
                    FieldValue: fieldValue,
                    FieldFilter: fieldFilter,
                    HLData: "",
                    HLType: "row",
                    HLAllow: "false",
                    column_data: "",
                    current_form_fields_data:[]
                };
                if (typeof $(container).attr('embed-hl-data') != "undefined") {
                    reference["HLData"] = $(container).attr('embed-hl-data');
                }
                if (typeof $(container).attr('allow-highlights') != "undefined") {
                    reference["HLAllow"] = $(container).attr('allow-highlights');
                }
                if (typeof $(container).attr('allow-highlights') != "undefined") {
                    reference["HLType"] = $(container).attr('highlight-type');
                }
                if (typeof $(container).attr('embed-column-data') != "undefined") {
                    reference["column_data"] = $(container).attr('embed-column-data');
                }

                $('#frmrequest').find(".setOBJ").each(function(eqi){
                    var data_object_id = $(this).attr("data-object-id");
                    var getFIELDS = $(this).find(".getFields_"+data_object_id);
                    var field_name = $(this).find(".getFields_"+data_object_id).eq(0).attr("name");
                    field_name_values = [];
                    getFIELDS.each(function(eqi2){
                        field_name_values.push($(this).val());
                    })
                    field_name_values = field_name_values.join("|^|");
                    reference["current_form_fields_data"].push({
                        "f_name":field_name,
                        "values":field_name_values
                    })
                })
                reference["current_form_fields_data"] = JSON.stringify(reference["current_form_fields_data"]);
                $(container).html('<center><img src="/images/loader/loader.gif" class="load-app-request" style="display: inline;margin-top:30px;"></center>');
                self.getRequests(reference, function(data) {
                    $(container).html(data);
                });
            }

            $('[name="' + fieldReference + '"]').change(function() {
                fieldValue = $(this).val();
                reference = {
                    FormID: formId,
                    FieldReferece: fieldReference,
                    FieldValue: fieldValue,
                    FieldFilter: fieldFilter,
                    HLData: "",
                    HLType: "row",
                    HLAllow: "false",
                    column_data: "",
                    current_form_fields_data:[]
                };
                if (typeof $(container).attr('embed-hl-data') != "undefined") {
                    reference["HLData"] = $(container).attr('embed-hl-data');
                }
                if (typeof $(container).attr('allow-highlights') != "undefined") {
                    reference["HLAllow"] = $(container).attr('allow-highlights');
                }
                if (typeof $(container).attr('allow-highlights') != "undefined") {
                    reference["HLType"] = $(container).attr('highlight-type');
                }
                if (typeof $(container).attr('embed-column-data') != "undefined") {
                    reference["column_data"] = $(container).attr('embed-column-data');
                }

                $('#frmrequest').find(".setOBJ").each(function(eqi){
                    var data_object_id = $(this).attr("data-object-id");
                    var getFIELDS = $(this).find(".getFields_"+data_object_id);
                    var field_name = $(this).find(".getFields_"+data_object_id).eq(0).attr("name");
                    field_name_values = [];
                    getFIELDS.each(function(eqi2){
                        field_name_values.push($(this).val());
                    })
                    field_name_values = field_name_values.join("|^|");
                    reference["current_form_fields_data"].push({
                        "f_name":field_name,
                        "values":field_name_values
                    })
                })
                reference["current_form_fields_data"] = JSON.stringify(reference["current_form_fields_data"]);
                $(container).html('<center><img src="/images/loader/loader.gif" class="load-app-request" style="display: inline;margin-top:30px;"></center>');
                self.getRequests(reference, function(data) {
                    console.log(data);
                    $(container).html(data);
                });
            });
        });
    },
    getRequests: function(reference, callback) {
        $.get('/ajax/embedded_view', reference, function(data) {
            callback(data);
        });
    }
};

var keyword_picklist = {
    init: function() {
        this.addEventListeners();
    },
    addEventListeners: function() {

    }
}

var computed = {
    init: function() {
        this.load();
    },
    load: function() {
        var self = this;
        var computedFields = [];
        var computedFieldPost = [];
        $('[data-type="computed"]').find('.getFields').each(function() {
            computedFields.push({
                FieldName: $(this).attr('name'),
                ProcessorType: $(this).attr('processor-type'),
                Processor: $(this).attr('processor')
            });
            computedFieldPost.push($(this).attr('name'));
        });

        $('#computedFields').val(JSON.stringify(computedFieldPost));

        var reference = {
            fields: JSON.stringify(computedFields)
        };
        ui.block();
        this.lookup(reference, function(data) {
            data = JSON.parse(data);
            console.log(data);
            for (var index in data) {
                $('[name="' + data[index].FieldName + '"]').attr('disabled', false);
                $('[name="' + data[index].FieldName + '"]').attr('readonly', true);
                $('[name="' + data[index].FieldName + '"]').val(data[index].Processor);
            }

            ui.unblock();
            embeded_view.init();
        });
    },
    lookup: function(reference, callback) {
        $.get('/ajax/request_computed_fields', reference, function(data) {
            callback(data);
        });
    }
};


var repeater = {
    getData: function() {
        var repeaterData = [];
        $('[repeater-table="true"]').each(function() {
            var objectId = $(this).closest('.setOBJ').attr('id');
            var row = [];

            $(this).find('tr').each(function(index) {
                var data = [];

                $(this).find('.getFields').each(function() {
                    var originalName = $(this).attr('rep-original-name');
                    var name = $(this).attr('name');
                    var type = $(this).attr('type');

                    switch (type) {
                        case "checkbox":
                            var values = [];
                            if ($(this).prop('checked')) {
                                values.push({
                                    Value: $(this).val(),
                                    Checked: true
                                });
                            } else {
                                values.push({
                                    Value: $(this).val(),
                                    Checked: false
                                });
                            }
                            break;
                        case "radio":
                            var values = [];
                            if ($(this).prop('checked')) {
                                values.push({
                                    Value: $(this).val(),
                                    Checked: true
                                });
                            } else {
                                values.push({
                                    Value: $(this).val(),
                                    Checked: false
                                });
                            }
                            break;
                        default :
                            if (typeof $(this).attr("data-input-type") != "undefined") {
                                if ($(this).attr("data-input-type") == "Currency") {
                                    var values = $(this).val().replace(/,/g, "");
                                } else {
                                    var values = $(this).val();
                                }
                            } else {
                                var values = $(this).val();
                            }
                            break;
                    }
                    if (index === 0) {
                        data.push({
                            FieldName: name,
                            Values: values
                        });
                    } else {
                        data.push({
                            FieldName: originalName,
                            Values: values
                        });
                    }
                });

                row.push({
                    Index: index,
                    Data: data
                });
            });


            repeaterData.push({
                ObjectId: objectId,
                Row: row
            });
        });

        console.log('REPEATER GET DATA',repeaterData);

        $('#Repeater_Data').val(JSON.stringify(repeaterData));
    },
    setData: function() {
        try {
            var content = JSON.parse($('#Repeater_Data').val());


            for (var index in content) {
                var objectId = content[index].ObjectId;
                for (var row in content[index].Row) {
                    if (row != 0) {
                        $('#' + objectId).find('.rep-add-spec-row:last').click();
                        $('#' + objectId).find('.rep-add-spec-row:last').parents("tbody").eq(0).children("tr").last().children("td").stop(true, true);
                    }
                    for (var data in content[index].Row[row].Data) {

                        var fieldName = content[index].Row[row].Data[data].FieldName;
                        var type = $('[name="' + fieldName + '"]').attr('type');
                        var field;
                        var values;

                        if (row == 0) {
                            field = $('[name="' + fieldName + '"]');
                        } else {
                            field = $('[name="' + fieldName + '_UID' + row + '"]');
                        }

                        switch (type) {
                            case "checkbox":
                                var values = content[index].Row[row].Data[data].Values[0].Value;
                                var checked = content[index].Row[row].Data[data].Values[0].Checked;
                                $(field).each(function() {
                                    var thisValue = $(this).val();

                                    if (values == thisValue) {
                                        $(this).prop('checked', checked);
                                    }

                                });
                                break;
                            case "radio":
                                var values = content[index].Row[row].Data[data].Values[0].Value;
                                var checked = content[index].Row[row].Data[data].Values[0].Checked;

                                $(field).each(function() {
                                    var thisValue = $(this).val();
                                    if (values == thisValue) {
                                        $(this).prop('checked', checked);
                                    }
                                });
                                break;
                            default :
                                values = content[index].Row[row].Data[data].Values;
                                $(field).val(values);
                                break;
                        }

                    }
                }
            }
        } catch (error) {
            console.log("error setData: function() { parsing json")
        }
    }
};

function setFieldsVisibility() {
    $('.getFields').each(function() {
        var visibility = $(this).attr('field-visible');

        switch (visibility) {
            case "true":
                $(this).parents('.setOBJ').eq(0).css('display', 'block');
                break;
            case "false":
                $(this).parents('.setOBJ').eq(0).css('display', 'none');
                break;
        }
    });

}

function computeVisibility() {
    if (typeof callBack == "undefined") {

    }
    var data = [];
    $('[field-visible="computed"]').each(function(index) {
        if ($(this).attr('visible-formula')) {
            var fieldName = $(this).attr('name');
            if (typeof fieldName == "undefined") {
                fieldName = $(this).attr('tab-name');
            }
            var formula = $(this).attr('visible-formula');
            var process_formula = formula;
            var getFieldName = formula.match(/@[A-Za-z_][A-Za-z0-9_]*/g);
            for (var ctr = 0; ctr < getFieldName.length; ctr++) {
                if ($('[name="' + getFieldName[ctr].replace("@", "") + '"]').length >= 1) {
                    var type = $('[name="' + getFieldName[ctr].replace("@", "") + '"]').attr('type');
                    if (type == 'radio') {
                        var value_fn = $('[name="' + getFieldName[ctr].replace("@", "") + '"]:checked').val();
                    } else {
                        var value_fn = $('[name="' + getFieldName[ctr].replace("@", "") + '"]').val();
                    }
                    process_formula = process_formula.replace(getFieldName[ctr], "'" + value_fn + "'");
                }
            }
            data.push({
                FieldName: fieldName,
                Formula: process_formula
            });
        }
    });
    // console.log("ETOOO BAAz");
    // console.log(data);

    for (var index in data) {
        var returnFieldName = data[index].FieldName;
        var returnFieldValue = eval(data[index].Formula);
        var role = "";
        if ($('[tab-name="' + returnFieldName + '"]').attr("role")) {
            role = $('[tab-name="' + returnFieldName + '"]').attr("role");
        }
        if (role.length >= 1 && role == "tab") {
            var tab_navigation_ele = $('[tab-name="' + returnFieldName + '"]');
            var content_id_ele = $('[tab-name="' + returnFieldName + '"]').children("a[role='presentation']").attr("href");
            if (returnFieldValue) {
                if (tab_navigation_ele.eq(0).css("display") == "none") {
                    tab_navigation_ele.eq(0).show();
                    $(content_id_ele).show();
                    tab_navigation_ele.eq(0).parents(".form-tabbable-pane").eq(0).css("height", "");
                    // tab_navigation_ele.eq(0).parents(".form-tabbable-pane").eq(0).css("width","");
                    tab_navigation_ele.eq(0).children("a").click();
                }
            } else {
                if (tab_navigation_ele.eq(0).css("display") != "none") {
                    tab_navigation_ele.eq(0).hide();
                    $(content_id_ele).hide();
                    if (tab_navigation_ele.eq(0).next().length >= 1 && tab_navigation_ele.eq(0).next().css("display") != "none") {
                        tab_navigation_ele.eq(0).next().children("a").click();
                    } else if (tab_navigation_ele.eq(0).prev().length >= 1 && tab_navigation_ele.eq(0).prev().css("display") != "none") {
                        tab_navigation_ele.eq(0).prev().children("a").click();
                    } else {
                        console.log("WALA NANG NAKA DISPLAY NA TAB")
                        // width_of_tab_panel = tab_navigation_ele.eq(0).parents(".setOBJ").eq(0).outerWidth();
                        height_of_tab = tab_navigation_ele.eq(0).css("height").replace("px", "");
                        height_of_tab_content = $(tab_navigation_ele.eq(0).children("a").eq(0).attr("href")).css("height").replace("px", "");
                        // console.log(tab_navigation_ele.eq(0).parents(".form-tabbable-pane").eq(0))
                        // console.log(width_of_tab_content+"  "+height_of_tab + "  " + height_of_tab_content)
                        tab_navigation_ele.eq(0).parents(".form-tabbable-pane").eq(0).css("height", (Number(height_of_tab) + Number(height_of_tab_content)) + "px")
                        // tab_navigation_ele.eq(0).parents(".form-tabbable-pane").eq(0).css("width",(width_of_tab_panel)+"px")
                        console.log(tab_navigation_ele.eq(0))
                    }
                }
            }
        } else {
            if (returnFieldValue) {
                // console.log("COMPUTE SPACES toblock", computeGap($('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0),'expand') );
                if($('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).attr("compute-visibility-display")){
                    $('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).css("display",$('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).attr("compute-visibility-display"));
                }else{
                    if($('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).css("display") != "none"){
                        $('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).css('display', $('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).css('display'));
                    }else{
                        $('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).css('display','block');
                    }
                }
            } else {
                // console.log("COMPUTE SPACES togap", computeGap($('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0),'collapse') );
                if($('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).css("display") != "none"){
                    $('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).attr("compute-visibility-display",$('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).css("display"));
                }
                $('[name="' + returnFieldName + '"]').parents('.setOBJ').eq(0).css('display', 'none');
                
            }
        }
    }
    checkStaticTablesGAP();
}































function checkStaticTablesGAP(){
    function collapseByRow(dis_ele){
        var collapse_elements = {
            "elem_to_collapse":null,
            "elem_to_expand":null
        };
        var selected_tbody = $(dis_ele).children("tbody").eq(0);
        var selected_trs = selected_tbody.children("tr");
        selected_trs.each(function(eq_trs){
            var row_total_field_setOBJ = $(this).find(".setOBJ")
            .filter(function(index,dom_ele){
                var looped_ele = $(dom_ele);
                var data_object_id = looped_ele.attr("data-object-id");
                var getFields_ele = looped_ele.find("#obj_fields_"+data_object_id);
                if(getFields_ele.length >= 1 ){
                    if(getFields_ele.find('[name]').length >= 1){
                        return true;
                    }else{ 
                        return false;
                    }
                }else{
                    return false;//wag iselect
                }
            });


            var row_total_field_hidden = $(this).find(".setOBJ")
            .filter(function(index,dom_ele){
                var looped_ele = $(dom_ele);
                var data_object_id = looped_ele.attr("data-object-id");
                var getFields_ele = looped_ele.find("#obj_fields_"+data_object_id);
                if(getFields_ele.length >= 1 ){
                    if(getFields_ele.find('[name]').length >= 1){
                        if(looped_ele.css("display") == "none"){
                            return true;
                        }else{
                            return false;
                        }
                    }else{ 
                        return false;
                    }
                }else{
                    return false;//wag iselect
                }
            });
            // console.log(eq_trs,"GRAA",row_total_field_setOBJ," === ",row_total_field_hidden);
            if(row_total_field_setOBJ.length >= 1){
                if(row_total_field_setOBJ.length == row_total_field_hidden.length){
                    $(this).children('td').stop(true,true);
                    if($(this).children('td').css("display") != "none"){
                        $(this).data("rVisibilityHeightTD",$(this).outerHeight());
                        // $(this).children('td').animate({
                        //     "height":0
                        // },function(){
                        //     $(this).css("display","none");
                        // })//ANIMATE
                        $(this).children('td').css({
                            "display":"none"
                        })
                        if(collapse_elements["elem_to_collapse"] != null){
                            collapse_elements["elem_to_collapse"] = $(collapse_elements["elem_to_collapse"].add($(this).children('td')) );
                        }else{
                            collapse_elements["elem_to_collapse"] = $($(this).children('td'));
                        }
                    }
                }else{
                    if($(this).data("rVisibilityHeightTD")){
                        height_rTD = $(this).data("rVisibilityHeightTD");
                        $(this).children('td').css("display","table-cell");
                        // $(this).children('td').filter(function(index, ele_dom){if($(ele_dom).attr("cvisibilitywidthtd")){return false;}else{return true;} }).stop(true,true).animate({
                        //     "height":height_rTD
                        // },function(){
                        //     $(this).css("display","table-cell");
                        // }) //ANIMATE
                        $(this).children('td').filter(function(index, ele_dom){if($(ele_dom).attr("cvisibilitywidthtd")){return false;}else{return true;} }).css({
                            "display":"table-cell"
                        }) //STATIC
                        if(collapse_elements["elem_to_expand"] != null){
                            collapse_elements["elem_to_expand"] = $(collapse_elements["elem_to_expand"].add($(this).children('td').filter(function(index, ele_dom){if($(ele_dom).attr("cvisibilitywidthtd")){return false;}else{return true;} }) ) );
                        }else{
                            collapse_elements["elem_to_expand"] = $($(this).children('td').filter(function(index, ele_dom){if($(ele_dom).attr("cvisibilitywidthtd")){return false;}else{return true;} }) );
                        }
                    }else{
                        $(this).children('td').filter(function(index, ele_dom){if($(ele_dom).attr("cvisibilitywidthtd")){return false;}else{return true;} }).css("display","table-cell");
                        
                    }
                }
            }
        })
        return collapse_elements;
    }
    function collapseByColumn(dis_ele){//COLUMN BASIS
        var selected_tbody = $(dis_ele).children("tbody").eq(0);
        var selected_trs = selected_tbody.children("tr");
        var total_columns = selected_trs.eq(0).children("td").length;
        for(var ii = 0; ii < total_columns; ii++){
            var selected_col = $(selected_trs.children("td").eq(ii));
            selected_trs.each(function(eq_trs){
                if(eq_trs != 0){
                    selected_col = selected_col.add($(this).children("td").eq(ii));
                }
            })

            
            var col_total_field_hidden = selected_col.find(".setOBJ").filter(function(index,dom_ele){
                var looped_ele = $(dom_ele);
                var data_object_id = looped_ele.attr("data-object-id");
                var getFields_ele = looped_ele.find("#obj_fields_"+data_object_id);
                if(getFields_ele.length >= 1 ){
                    if(getFields_ele.find('[name]').length >= 1){
                        if(looped_ele.css("display") == "none"){
                            return true;
                        }else{
                            return false;
                        }
                    }else{ 
                        return false;
                    }
                }else{
                    return false;//wag iselect
                }
            });


            var col_total_field_setOBJ = selected_col.find(".setOBJ").filter(function(index,dom_ele){
                var looped_ele = $(dom_ele);
                var data_object_id = looped_ele.attr("data-object-id");
                var getFields_ele = looped_ele.find("#obj_fields_"+data_object_id);
                if(getFields_ele.length >= 1 ){
                    if(getFields_ele.find('[name]').length >= 1){
                        return true;
                    }else{ 
                        return false;
                    }
                }else{
                    return false;//wag iselect
                }
            });

            console.log("COLUMN "+ii+"::",selected_col);
            console.log("COLUMN SETOBJ"+ii+"::",selected_col.find(".setOBJ"));
            if(col_total_field_setOBJ.length == col_total_field_hidden.length){
                selected_col.stop(true,true);
                if(selected_col.css("display") != "none"){
                    selected_col.attr("cVisibilityWidthTD",selected_col.filter(function(index, elem_dom){
                        if($(elem_dom).css("display") != "none"){
                            return true;
                        }else{
                            return false;
                        }
                    }).outerWidth());

                    // selected_col.animate({
                    //     "width":0
                    // },function(){
                    //     console.log("NONE",$(this).css("display","none")    )
                    // });//animate
                    selected_col.css("display","none");
                }
                
                // selected_col.stop(true,true);
                // if(selected_col.css("display") != "none"){
                //     $(this).data("rVisibilityHeightTD",$(this).outerHeight());
                // }
                // $(this).children('td').animate({
                //     "height":0
                // },function(){
                //     $(this).css("display","none");
                // })
            }else{
                // alert(selected_col.css("display"))
                // console.log("BABA",selected_col);
                // var showed_ele_td = selected_col.filter(function(index, dom_ele){
                //     if($(this).css("display") != "none" && !$(this).parents("tr").eq(0).data("rVisibilityHeightTD")){
                //         return true;
                //     }else{
                //         return false;
                //     }
                // }).length;


                // if(showed_ele_td == 0 ){
                    
                // }else if(showed_ele_td >= 1){
                //     var load_td_width = selected_col.attr("cVisibilityWidthTD");
                //     selected_col.css("display","table-cell");
                // }
                var showed_ele_td = selected_col.filter(function(index, dom_ele){
                    if($(this).css("display") != "none" && !$(this).parents("tr").eq(0).data("rVisibilityHeightTD")){
                        return true;
                    }else{
                        return false;
                    }
                }).length;
                if(showed_ele_td == 0){
                    var load_td_width = selected_col.attr("cVisibilityWidthTD");
                    selected_col.css("display","table-cell");
                }
            }
        }

        // selected_trs.each(function(eq_trs){

        //     var selected_tds = $(this).children("td");
        // })
        return {};
    }
    $(".form-table.thisDynamicTable").each(function(eq_table){
        var row_elems = collapseByRow($(this));
        // var col_elems = collapseByColumn($(this));


        // if(row_elems["elem_to_collapse"] != null){
        //     row_elems["elem_to_collapse"].each(function(){
        //         $(this).parents("tr").eq(0).attr("rVisibilityHeightTD",$(this).parents("tr").eq(0).outerHeight());
        //     })
        //     row_elems["elem_to_collapse"].animate({
        //         height:0
        //     },function(){
        //         if(row_elems["elem_to_expand"] != null){
        //             row_elems["elem_to_expand"].animate({
        //                 height:62   
        //             })
        //         }
        //     })
        // }
        // if(row_elems["elem_to_expand"] != null){
        //     row_elems["elem_to_expand"].animate({
        //         height:62   
        //     })
        // }
    })
}

function computeGap(cg_element_passed,type){
    if(type == "collapse"){
        // alert("MY NAME IS "+$(cg_element_passed).find(".getFields").eq(0).attr("name"))
        // unPaintAll('.setOBJ');
        // unShadowAll('.setOBJ');
        collapseBelow(cg_element_passed);
    }else if(type == "expand"){
        // unPaintAll('.setOBJ');
        // unShadowAll('.setOBJ');
        expandBelow(cg_element_passed);
    }
}

function collapseBelow(cg_element_passed){
    var ele_selected = $(cg_element_passed);
    var adjust_value = ele_selected.outerHeight(); //BY PX
    
    var eles_below = selectEleBelow.call( getDataCoor(ele_selected) , ele_selected);

    for(index_below in eles_below){
        // paintELEM(eles_below[index_below]["selectedElement"],"red");

        var eles_above = selectEleAbove.call( eles_below[index_below] , eles_below[index_below]["selectedElement"]);
        

        var a_below = getDataCoor(eles_below[index_below]["selectedElement"]);
        var b_above = getDataCoor(eles_above[0]["selectedElement"]);
        if(ele_selected.index() == b_above["selectedElement"].index()){
            if(eles_above.length == 1){
                b_above = getDataCoor($(""));
            }else{
                b_above = getDataCoor(eles_above[1]["selectedElement"]);
            }
        }
        
        var gap_above =  a_below["getPosTop"] - b_above["getPosBottom"];
        // alert(gap_above+" >= "+adjust_value)
        if(gap_above >= adjust_value){
            var top_of_elem_to_adjust = $(eles_below[index_below]["selectedElement"]).css("top").replace("px","");
            if($(eles_below[index_below]["selectedElement"]).data("computeGapData") === undefined){
                $(eles_below[index_below]["selectedElement"]).css({
                    "top":(Number(top_of_elem_to_adjust) - adjust_value)+"px"
                });
                $(eles_below[index_below]["selectedElement"]).data("computeGapData",{
                    "moveByOBJID":$(ele_selected).attr("data-object-id"),
                    "adjustedValue":adjust_value,
                    "affectType":"collapse"
                });
            }else{
                $(eles_below[index_below]["selectedElement"]).data("computeGapData",{
                    "moveByOBJID":$(ele_selected).attr("data-object-id"),
                    "adjustedValue":adjust_value,
                    "affectType":"collapse"
                });
            }
            // shadowELEM($(eles_below[index_below]["selectedElement"]),"black");
        }
    }
}
function expandBelow(cg_element_passed){
    var ele_selected = $(cg_element_passed); //EPICENTER
    var collect_elem_to_expand = [];
    var selected_obj_with_data = $('.setOBJ').filter(function(){
        return ($(this).data("computeGapData") !== undefined); //NEW DISCOVERY ... SELECTOR THAT HAS A DATA computeGapData
    });
    // console.log("EXPAND GREAT DATA FILTER NEW DISCOVERY",selected_obj_with_data);
    selected_obj_with_data.each(function(){
        collect_elem_to_expand.push(getDataCoor($(this)));
		//shadowELEM($(this),"green");
    });
    collect_elem_to_expand = sortDescMyObjectByKey(collect_elem_to_expand, "getPosTop"); //collect_elem_to_expand sort by the most top
    for(index_key in collect_elem_to_expand){
        var dis_elem_to_expand = collect_elem_to_expand[index_key];
        var elem_to_expand = getDataCoor(dis_elem_to_expand["selectedElement"]);

        if(elem_to_expand["selectedElement"].data("computeGapData") !== undefined){
            var eleExpand_computeGapData = elem_to_expand["selectedElement"].data("computeGapData");
            if(eleExpand_computeGapData["affectType"] == "collapse"){
                if(eleExpand_computeGapData["moveByOBJID"] == $(ele_selected).attr("data-object-id")){
                    console.log("ELEM EXPAND ",elem_to_expand["selectedElement"]);
                    // alert(234)
                    var ele_below = selectEleBelow.call(getDataCoor(elem_to_expand["selectedElement"]),elem_to_expand["selectedElement"]);
                    if(ele_below.length >= 1 ){

                        var b_to_expand = getDataCoor(elem_to_expand["selectedElement"]);
                        var a_below_of_to_expand = getDataCoor(ele_below[0]["selectedElement"]);
                        if(a_below_of_to_expand["selectedElement"].index() != ele_selected.index()){
                            var gap_below =  a_below_of_to_expand["getPosTop"] - b_to_expand["getPosBottom"];
                            // alert("TAAS" + a_below_of_to_expand["getPosTop"]+" - "+b_to_expand["getPosBottom"])
                            if(gap_below >= eleExpand_computeGapData["adjustedValue"]){
                                b_to_expand["selectedElement"].css({
                                    "top":( b_to_expand["getPosTop"] + eleExpand_computeGapData["adjustedValue"] )+"px"
                                });
                            }
                        }else{
                            // alert("BABA")
                            elem_to_expand["selectedElement"].css({
                                "top":( elem_to_expand["getPosTop"] + eleExpand_computeGapData["adjustedValue"] )+"px"
                            });
                        }

                        // console.log('COMPUTE',ele_below)
                        // var a_below = getDataCoor(ele_below[0]["selectedElement"]);
                        // var b_above = getDataCoor(elem_to_expand["selectedElement"]);
                        // var gap_below = a_below["getPosTop"] - b_above["getPosBottom"]; //DTO NA KO
                        // alert("GAP ABOVE"+a_below["selectedElement"].attr("data-object-id")+" - "+b_above["selectedElement"].attr("data-object-id"))
                        // elem_to_expand = getDataCoor(elem_to_expand["selectedElement"]);
                        // shadowELEM(elem_to_expand["selectedElement"],"blue");
                        // alert("OK "+gap_below+" >= "+eleExpand_computeGapData["adjustedValue"]);
                        // if(gap_below >= eleExpand_computeGapData["adjustedValue"]){
                        //     elem_to_expand["selectedElement"].css({
                        //         "top":( elem_to_expand["getPosTop"] + eleExpand_computeGapData["adjustedValue"] )+"px"
                        //     });
                        // }
                    }else{
                        elem_to_expand["selectedElement"].css({
                            "top":( elem_to_expand["getPosTop"] + eleExpand_computeGapData["adjustedValue"] )+"px"
                        });
                    }
                    $(elem_to_expand["selectedElement"]).removeData("computeGapData");
                }
            }
        }
    }



    // var dis_compute_gap_data = $(this).data("computeGapData");
        // if(dis_compute_gap_data["moveByOBJID"] == $(ele_selected).attr("data-object-id")){ //IF THE EPICENTER HAS A MARK ON THE MOVE ELEMENT //IBIG SABIHIN SYA UNG NAG PAGALAW DUN SA ELEMENT NA UN :D
        //     console.log("EXPAND", $(this))
        //     if(dis_compute_gap_data["affectType"] == "collapse"){ //PAG NAKITA NA NAKA COLLAPSE THEN UN UNG MGA EEXPAND
        //         shadowELEM($(eles_below[index_below]["selectedElement"]),"blue");
        //         $(this).css({
        //             "top":($(this).position().top + dis_compute_gap_data["adjustedValue"] )+"px"
        //         });
        //         $(this).data("computeGapData",{
        //             "moveByOBJID":$(ele_selected).attr("data-object-id"),
        //             "adjustedValue":adjust_value,
        //             "affectType":"expand"
        //         });
        //         $(this).removeData( "computeGapData" );
                
        //     }
        // }

}

function getDataCoor(element_passed){
    var element_set = $(element_passed);

    var ESet_coorData = { //INITIALIZE
        "getOffTop":0,
        "getOffLeft":0,
        "getOffRight":0,
        "getOffBottom":0,

        "getPosTop":0,
        "getPosLeft":0,
        "getPosRight":0,
        "getPosBottom":0,

        "getOuterWidth":0,
        "getOuterHeight":0,

        "selectedElement":element_set
    }
    
    if(element_set.length >= 1 ){
        if(element_set.css("display") == "none"){
            ESet_coorData = {
                "getOffTop":/*Number(element_set.css("top").replace('px','') )*/null,
                "getOffLeft":/*Number(element_set.css("left").replace('px','') )*/null,
                "getOffRight":/*Number(element_set.css("left").replace('px','') ) + element_set.outerWidth()*/null,
                "getOffBottom":/*Number(element_set.css("top").replace('px','') ) + element_set.outerHeight()*/null,

                "getPosTop":Number(element_set.css("top").replace('px','') ),
                "getPosLeft":Number(element_set.css("left").replace('px','') ),
                "getPosRight":Number(element_set.css("left").replace('px','') ) + element_set.outerWidth(),
                "getPosBottom":Number(element_set.css("top").replace('px','') ) + element_set.outerHeight(),

                "getOuterWidth":element_set.outerWidth(),
                "getOuterHeight":element_set.outerHeight(),

                "selectedElement":element_set
            }
        }else{
            ESet_coorData = {
                "getOffTop":element_set.offset().top,
                "getOffLeft":element_set.offset().left,
                "getOffRight":element_set.offset().left + element_set.outerWidth(),
                "getOffBottom":element_set.offset().top + element_set.outerHeight(),

                "getPosTop":element_set.position().top,
                "getPosLeft":element_set.position().left,
                "getPosRight":element_set.position().left + element_set.outerWidth(),
                "getPosBottom":element_set.position().top + element_set.outerHeight(),

                "getOuterWidth":element_set.outerWidth(),
                "getOuterHeight":element_set.outerHeight(),

                "selectedElement":element_set
            }
        }
    }
    
    return ESet_coorData;
}
function selectEleBelow(epicenter_ele){
    console.log("OHH THIS: ",this)
    var collectSelEleBelow = [];
    var ele_selected = $(epicenter_ele);

    var epicenter_data = this;
    var collect_all_coor_data = [];

    collect_all_coor_data.push(epicenter_data);

    var condition_most_left = epicenter_data["getPosLeft"];
    var condition_most_right = epicenter_data["getPosRight"];

    ele_selected.parent().children('.setOBJ').each(function(){ //COLLECT COOR DATA
        var each_elem_data = getDataCoor($(this));
        collect_all_coor_data.push(each_elem_data);
    });

    collect_all_coor_data = sortMyObjectByKey(collect_all_coor_data, "getPosTop"); //ALL COOR DATA SORT BY TOP

    for(value in collect_all_coor_data){
        each_elem_data = collect_all_coor_data[value];
		//paintELEM(each_elem_data["selectedElement"],"red"); //DEBUG TOOLS
		//alert(1)
        if(epicenter_data["selectedElement"].index() != each_elem_data["selectedElement"].index()){ // EXCLUDE EPICENTER INDEX
            if(each_elem_data["getPosBottom"] > epicenter_data["getPosTop"]){ // GET ELEMENT BELOW FROM EPICENTER
                if(each_elem_data["getPosRight"] > condition_most_left && each_elem_data["getPosLeft"] < condition_most_right){ // GET AFFECTED PARALLEL BELOW
                    if(each_elem_data["getPosLeft"] < condition_most_left){ //GET MOST LEFT
                        condition_most_left = each_elem_data["getPosLeft"];
                    }
                    if(each_elem_data["getPosRight"] > condition_most_right){ //GET MOST RIGHT
                        condition_most_right = each_elem_data["getPosRight"];
                    }
                    
					
                    collectSelEleBelow.push(each_elem_data);
                }
            }
        }
    }
    collectSelEleBelow = sortMyObjectByKey(collectSelEleBelow, "getPosTop"); //ALL COOR DATA SORT BY TOP
    return collectSelEleBelow;
}
function selectEleAbove(epicenter_ele){
    var collectSelEleAbove = [];


    var ele_selected = $(epicenter_ele);

    var epicenter_data = this;
    var collect_all_coor_data = [];

    collect_all_coor_data.push(epicenter_data);

    var condition_most_left = epicenter_data["getPosLeft"];
    var condition_most_right = epicenter_data["getPosRight"];

    ele_selected.parent().children('.setOBJ').each(function(){ //COLLECT COOR DATA
        var each_elem_data = getDataCoor($(this));
        collect_all_coor_data.push(each_elem_data);
    });

    collect_all_coor_data = sortDescMyObjectByKey(collect_all_coor_data, "getPosTop"); //ALL COOR DATA SORT BY TOP

    for(value in collect_all_coor_data){
        each_elem_data = collect_all_coor_data[value];
        console.log(each_elem_data["getPosTop"]);
        if(epicenter_data["selectedElement"].index() != each_elem_data["selectedElement"].index()){ // EXCLUDE EPICENTER INDEX
            if(each_elem_data["getPosBottom"] < epicenter_data["getPosTop"]){ // GET ELEMENT ABOVE FROM EPICENTER
                if(each_elem_data["getPosRight"] > condition_most_left && each_elem_data["getPosLeft"] < condition_most_right){ // GET AFFECTED PARALLEL ABOVE
                    if(each_elem_data["getPosLeft"] < condition_most_left){ //GET MOST LEFT
                        condition_most_left = each_elem_data["getPosLeft"];
                    }
                    if(each_elem_data["getPosRight"] > condition_most_right){ //GET MOST RIGHT
                        condition_most_right = each_elem_data["getPosRight"];
                    }
                    //paintELEM(each_elem_data["selectedElement"],"red"); //DEBUG TOOLS
                    collectSelEleAbove.push(each_elem_data);
                }
            }
        }
        
    }
    return collectSelEleAbove;
}















//DEBUG TOOLS
function paintELEM(element, color){
    $(element).css("outline","1px solid "+color);
}
function shadowELEM(element,color){
    $(element).css("box-shadow","0px 0px 10px "+color);
}
function unShadowAll(element){
    $(element).css("box-shadow","");
}
function unPaintAll(element){
    $(element).css("outline","");
}
function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getRandomArbitary (min, max) {
    return Math.random() * (max - min) + min;
}

function sortMyObjectByKey(arrayObject, keyNameValToSort) {
    var myArrayOfObj = arrayObject;
    // myArrayOfObj.sort(function (a, b) {
    //     if (a[keyNameValToSort] < b[keyNameValToSort]) {
    //         return -1;
    //     }
    //     else if (a[keyNameValToSort] > b[keyNameValToSort]) {
    //         return 1;
    //     }
    //     return 0;
    // });
    // return myArrayOfObj;
    return myArrayOfObj.sort(function(x, y) {
        return x[keyNameValToSort] - y[keyNameValToSort]
    });
}
function sortDescMyObjectByKey(arrayObject, keyNameValToSort) {
    var myArrayOfObj = arrayObject;
    
    return myArrayOfObj.sort(function(x, y) {
        return y[keyNameValToSort] - x[keyNameValToSort];
    });
}